//
//  GameLayer.m
//  Soccer
//
//  Created by Hyun-Woong Kim on 09. 04. 28.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "GameLayer.h"
#import "Constant.h"
#import "ClientManager.h"

@implementation GameLayer

@synthesize goalIn;
@synthesize bgTrack;

- (id)init
{	
	if (self = [super init])
	{
		sprites = [[NSMutableArray array] retain];
		[self schedule:@selector(tick:) interval:1.0f/frameRate];
		
//		// init sound manager/OpenAL support
        [PASoundMgr sharedSoundManager];
        // preload interface-like sounds
//        bgTrack = [[PASoundMgr sharedSoundManager] addSound:@"trance-loop" withExtension:@"ogg" position:CGPointZero looped:YES];
		goalIn = [[PASoundMgr sharedSoundManager] addSound:@"goalIn" withExtension:@"wav" position:CGPointZero looped:NO];
//		effect1 = [[PASoundMgr sharedSoundManager] addSound:@"chicken" withPosition:CGPointZero looped:NO];
//        
        // lower music track volume and play it
//        [bgTrack setGain:0.3f];
//        [bgTrack playAtListenerPosition];
//		
//		[effect1 setGain:0.5f];
	}
	return self;
}

- (void)dealloc
{
	[self unschedule:@selector(tick:)];

//	[bgTrack stop];
//	[bgTrack release];
//	[effect1 stop];
//	[effect1 release];
	
	[sprites release];
	
	[super dealloc];
}

- (void)objectAdded:(Object *)object
{
	ObjectSprite *sprite = [[ObjectSprite alloc] initWithDelegate:object];
	[sprites addObject:sprite];
	
	if ([object isKindOfClass:[Stadium class]])
	{
		stadium = sprite;
		[self addChild:sprite];
	}
	else if ([object isKindOfClass:[MiniMap class]])
	{
		miniMapSprite = sprite;
		[self addChild:sprite];
			
		sprite.position = ((MiniMap *) object).position;
	}
	else
	{
		[stadium addChild:sprite];
		Sprite* spriteAdd;

		// Player인 경우 처리
		if ([object isKindOfClass:[Player class]])
		{
			Player* myself = [ClientManager sharedManager].match.myself;
			
			// player에 해당하는 sprite 생성후 미니맵에 add
			Player* player = (Player *)object;
			NSString* filename;
			
			if (player == myself)
			{
				filename = @"black.png";
			}
			else
			{
				if(player.team == TeamA)
					filename = @"red.png";
				else
					filename = @"blue.png";
			}
			
			// player에 해당되는 Sprite 객체 생성
			spriteAdd = [Sprite spriteWithFile:filename];
			player.miniMapPlayer = spriteAdd;
		}
		// Ball인 경우 처리
		else if ([object isKindOfClass:[Ball class]])
		{
			Ball* ball = (Ball *)object;
			// ball에 해당되는 Sprite 객체 생성
			spriteAdd = [Sprite spriteWithFile:@"white.png"];
			ball.miniMapBall = spriteAdd;
		}
			
		if (spriteAdd != nil)
			[miniMapSprite addChild:spriteAdd];
	}
	
	[sprite release];
}

// Main display loop //
- (void)tick:(ccTime)dt
{
	for (ObjectSprite *sprite in sprites)
	{
		[sprite updatePosition];
	}
}

@end
